#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:teacher_dao.py
# author:张世航
# datetime:2024/12/20 23:50
# software: PyCharm
"""
this is function  description 
"""
# import module your need
# dao/teacher_dao.py
import pymysql
from config.config import DATABASE_CONFIG
from models.teacher import Teacher

def connect_db():
    """连接数据库"""
    try:
        connection = pymysql.connect(**DATABASE_CONFIG)
        return connection
    except pymysql.MySQLError as e:
        print(f"Error connecting to database: {e}")
        return None

def add_teacher(teacher):
    """添加教师信息"""
    connection = connect_db()
    if connection:
        try:
            with connection.cursor() as cursor:
                sql = "INSERT INTO teacher (Tno, Tname, Dno, Salary, Tmobile) VALUES (%s, %s, %s, %s, %s)"
                cursor.execute(sql, (teacher.Tno, teacher.Tname, teacher.Dno, teacher.Salary, teacher.Tmobile))
                connection.commit()
                print("Teacher added successfully.")
        except pymysql.MySQLError as e:
            connection.rollback()
            print(f"Error adding teacher: {e}")
        finally:
            connection.close()

def delete_teacher(Tno):
    """根据教师编号删除信息"""
    connection = connect_db()
    if connection:
        try:
            with connection.cursor() as cursor:
                sql = "DELETE FROM teacher WHERE Tno = %s"
                cursor.execute(sql, (Tno,))
                connection.commit()
                print("Teacher deleted successfully.")
        except pymysql.MySQLError as e:
            connection.rollback()
            print(f"Error deleting teacher: {e}")
        finally:
            connection.close()

def query_teacher_by_name(name):
    """根据教师姓名查询信息"""
    connection = connect_db()
    if connection:
        try:
            with connection.cursor() as cursor:
                sql = "SELECT * FROM teacher WHERE Tname = %s"
                cursor.execute(sql, (name,))
                results = cursor.fetchall()
                for row in results:
                    print(row)
        except pymysql.MySQLError as e:
            print(f"Error querying teacher: {e}")
        finally:
            connection.close()